package com.baitiaojun.video.support;

import com.baitiaojun.api.util.ConstantUtil;
import com.baitiaojun.api.util.TokenUtil;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * @类名 UserSupport
 * @描述
 * @作者 白条君
 * @创建日期 2022/10/26 23:05
 * @版本 1.0
 */
@Component
public class UserSupport {

    @Resource
    private RedisSupport redisSupport;

    public String getToken(HttpServletRequest httpServletRequest) {
        ServletServerHttpRequest request = new ServletServerHttpRequest(httpServletRequest);
        HttpHeaders headers = request.getHeaders();
        return Objects.requireNonNull(headers.get(ConstantUtil.Field.AUTHORIZATION.getKey())).get(0);
    }

    public Object getCurrentUser(HttpServletRequest httpServletRequest) {
        String token = getToken(httpServletRequest);
        return redisSupport.getHash(token, ConstantUtil.Field.USER_AND_USERINFO.getKey());
    }

    public Long getCurrentUserId(HttpServletRequest httpServletRequest) throws Exception {
        String token = getToken(httpServletRequest);
        return TokenUtil.verifyToken(token);
    }
}